package com.ming.common.beetl.util;

import com.beetl.sql.dynamic.DynamicEntityLoader;
import com.ming.common.beetl.config.MySqlStyle;
import com.ming.common.beetl.entity.BaseEntity;
import com.ming.common.beetl.entity.DataSourceEntity;
import com.ming.common.beetl.entity.SQLManagerEntity;
import com.zaxxer.hikari.HikariDataSource;
import org.beetl.sql.core.*;
import org.beetl.sql.core.query.LambdaQuery;
import org.beetl.sql.ext.DebugInterceptor;

public class SqlUtil {

    public static HikariDataSource buildHikariDataSource(DataSourceEntity dataSourceEntity){
        HikariDataSource ds = new HikariDataSource();
        ds.setDriverClassName(dataSourceEntity.getDriverClassName());
        ds.setJdbcUrl(dataSourceEntity.getJdbcUrl());
        ds.setUsername(dataSourceEntity.getUsername());
        ds.setPassword(dataSourceEntity.getPassword());
        return ds;
    }

    public static SQLManager buildSQLManager(SQLManagerEntity entity){
        //得到一个ConnectionSource， 单数据源
        ConnectionSource source = ConnectionSourceHelper.getSingle(entity.getDataSource());
        //SQLManagerBuilder 唯一必须的参数就是ConnectionSource
        SQLManagerBuilder builder = new SQLManagerBuilder(source);
        //命名转化，数据库表和列名下划线风格，转化成Java对应的首字母大写，比如create_time 对应ceateTime
        builder.setNc(new UnderlinedNameConversion());
        //拦截器，非必须，这里设置一个debug拦截器，可以详细查看执行后的sql和sql参数
        builder.setInters(new Interceptor[]{new DebugInterceptor()});
        //数据库风格，因为用的是H2,所以使用H2Style,
        builder.setDbStyle(new MySqlStyle());
        SQLManager sqlManager = builder.build();
        if(entity.getInitSql() != null){
            //DBInitHelper.executeSqlScript(sqlManager,entity.getInitSql());
        }
        return sqlManager;
    }

    public static DynamicEntityLoader<BaseEntity> dynamicEntityLoader(SQLManager sqlManager){
        return new DynamicEntityLoader(sqlManager);
    }

    public static Class<? extends BaseEntity> dynamicEntity(SQLManager sqlManager, String tableName){
        DynamicEntityLoader<BaseEntity> dynamicEntityLoader = dynamicEntityLoader(sqlManager);
        Class<? extends BaseEntity> clazz = dynamicEntityLoader.getDynamicEntity(tableName, BaseEntity.class);
        return clazz;
    }

    public static LambdaQuery<? extends BaseEntity> dynamicLambdaQuery(SQLManager sqlManager,String tableName){
        Class<? extends BaseEntity> clazz = dynamicEntity(sqlManager, tableName);
        LambdaQuery<? extends BaseEntity> query = sqlManager.lambdaQuery(clazz);
        return query;
    }

    public static LambdaQuery dynamicLambdaQuery(SQLManager sqlManager,Class<? extends BaseEntity> clazz){
        LambdaQuery query = sqlManager.lambdaQuery(clazz);
        return query;
    }
}
